package com.jl.sms;

import com.jl.util.HexUtil;

public class TPAddress implements TransferLayerProtocol{

	private String address;
	private byte type = (byte) 0x81;

	/**
	 * 
	 * @param address example : 15998152018
	 */
	public TPAddress(String address){
		this.address = address.trim();
	}
	/**
	 * 
	 * @param _value Length(Number) + Type + data : 0B 81 51 99 18 25 10 F8 
	 */
	public TPAddress(byte[] _value){
		String value = HexUtil.toHexCompact(_value);
		type = HexUtil.parseHexToByte(value.substring(2,4));
		value = value.substring(4);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < value.length(); i += 2) {
			if(i + 1 < value.length() && value.charAt(i + 1) != 'F'){
				sb.append(value.charAt(i + 1));
			}
			if(value.charAt(i) != 'F'){
				sb.append(value.charAt(i));
			}
		}
		address = sb.toString();
	}
	
	/**
	 * @return byte[] Length(Number) + Type + data : 0B 81 51 99 18 25 10 F8 
	 */
	@Override
	public byte[] value() {
		StringBuilder res = new StringBuilder(HexUtil.toHexXX(address.length()));
		res.append(HexUtil.toHexXX(type & 0xFF));
		for (int i = 0; i < address.length(); i += 2) {
			if (i + 1 == address.length()) {
				res.append("F");
			} else {
				res.append(address.charAt(i + 1));
			}
			res.append(address.charAt(i));
		}
		return HexUtil.parseHexToByteArray(res.toString());
	}

	/**
	 * @return String example : 15998152018
	 */
	@Override
	public String valueAsString() {
		return address;
	}

}
